﻿using Inovout.RedictUrls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Inovout.Account.Web.Filters
{
    public class ProtectedAction : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            string datetime = filterContext.HttpContext.Request.QueryString["datetime"];
            string email = filterContext.HttpContext.Request.QueryString["email"];
            string key = filterContext.HttpContext.Request.QueryString["key"];
            //客户端IP和时间戳进行MD5加密
            string currentTimeStamp = ConvertDateTimeInt(DateTime.Now).ToString();
            string currentkey = MD5Encoding(GetLocalhostIp() + datetime);
            if (currentkey == key && GetTime(datetime).AddMinutes(2) <= DateTime.Now)
            {
                filterContext.Controller.ViewBag.ValidationResult = true;
            }
            else
            {
                filterContext.Controller.ViewBag.ValidationResult = false;
            }
            base.OnActionExecuting(filterContext);
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            string actionurl = filterContext.HttpContext.Request.QueryString["actionurl"];
            IRedictUrlService redictUrlServcie = Inovout.ComponentRegistry.Resolve<IRedictUrlService>();
            RedirctUrl redirctUrl = redictUrlServcie.FindByActionUrl(actionurl);
            redirctUrl.ValidNumber += 1;
            redictUrlServcie.Save(redirctUrl);
            base.OnActionExecuted(filterContext);
        }

        private string GetLocalhostIp()
        {
            String strHostName = string.Empty;
            // Getting Ip address of local machine...
            // First get the host name of local machine.
            strHostName = Dns.GetHostName();
            Console.WriteLine("Local Machine's Host Name: " + strHostName);
            // Then using host name, get the IP address list..
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
            IPAddress[] addr = ipEntry.AddressList;
            return addr[0].ToString();
        }

        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time"> DateTime时间格式</param>
        /// <returns>Unix时间戳格式</returns>
        private int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name="timeStamp">Unix时间戳格式</param>
        /// <returns>C#格式时间</returns>
        public static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        /// <summary>
        /// MD5 加密字符串
        /// </summary>
        /// <param name="rawPass">源字符串</param>
        /// <returns>加密后字符串</returns>
        private string MD5Encoding(string rawPass)
        {
            // 创建MD5类的默认实例：MD5CryptoServiceProvider
            MD5 md5 = MD5.Create();
            byte[] bs = Encoding.UTF8.GetBytes(rawPass);
            byte[] hs = md5.ComputeHash(bs);
            StringBuilder sb = new StringBuilder();
            foreach (byte b in hs)
            {
                // 以十六进制格式格式化
                sb.Append(b.ToString("x2"));
            }
            return sb.ToString();
        }

    }
}